package br.com.windroid.conceitows;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import util.Singleton;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class EnderecoIpFormActivity extends Activity {

	EditText enderecoIpEdit;
	Button botaoSalvar;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.endereco_ip);

	
		enderecoIpEdit = (EditText) findViewById(R.id.ipEditText);
		botaoSalvar = (Button) findViewById(R.id.salvarButton);
		
		enderecoIpEdit.setText("10.0.2.2");
		acaoBotaoSalvar();
	}

	@SuppressLint("ShowToast")
	private void acaoBotaoSalvar(){
		botaoSalvar.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String ip = enderecoIpEdit.getText().toString();
				boolean ping = false;
				try {
					
					InetAddress address = InetAddress.getByName(ip);
					
					if (address.isReachable(1000)){	
						Toast.makeText(EnderecoIpFormActivity.this, "IP Respondendo", Toast.LENGTH_LONG).show();
						Singleton.getInstance().setIpServidor(ip);
						Intent intent = new Intent(EnderecoIpFormActivity.this,UsuarioListActivity.class);
						startActivity(intent);
					}else{
						Toast.makeText(EnderecoIpFormActivity.this, "IP Não Respondendo", Toast.LENGTH_LONG).show();
					}
					
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.option, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * Evento disparado ao selecionar item do menu
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.add) {
			startActivity(new Intent(this,UsuarioFormActivity.class));
			return true;
		}
		if (item.getItemId() == R.id.listarUsuario) {
			startActivity(new Intent(this,UsuarioListActivity.class));
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
